import sun.reflect.generics.tree.Tree;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:二叉树的实现
 * User: Solitudefire
 * Date: 2022-05-16
 * Time: 21:08
 */
class TreeNode {
    public char val;
    public TreeNode left;//左孩子的引用
    public TreeNode right;//右孩子的引用

    public TreeNode(char val) {
        this.val = val;
    }
}

public class BinaryTree {
    public TreeNode root;//二叉树的根节点
    int count = 0;

    /**
     * 这种方式是以穷举。
     *
     * @return
     */
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;
    }

//    public static int i = 0;
//
//    public static TreeNode createTree(String str) {
//        TreeNode root = null;
//        if(str.charAt(i) != '#'){
//            root = new TreeNode(str.charAt(i));
//            i++;
//            root.left = createTree(str);
//            root.right = createTree(str);
//        }else{
//            //遇到# 就是空树
//            i++;
//        }
//        return root;
//    }
//
//    public  static void inorder(TreeNode root){
//        if (root == null){
//            return ;
//        }
//        inorder(root.left);
//        System.out.print(root.val+" ");
//        inorder(root.right);
//    }
//
//    public static void main(String[] args) {
//        Scanner in = new Scanner(System.in);
//        // 注意 hasNext 和 hasNextLine 的区别
//        while (in.hasNextLine()) { // 注意 while 处理多个 case
//            String str = in.nextLine();
//            TreeNode root = createTree(str);
//            inorder(root);
//        }
//    }

    public List<Character> postorderTraversal(TreeNode root) {
        List<Character> retlist = new ArrayList<>();
        if (root == null) {
            return retlist;
        }
        List<Character> leftTree = postorderTraversal(root.left);
        retlist.addAll(leftTree);
        List<Character> rightTree = postorderTraversal(root.right);
        retlist.addAll(rightTree);
        retlist.add(root.val);
        return retlist;
    }


    //中序遍历
    public void inOrderTraversal(TreeNode root) {
        if (root != null) {
            inOrderTraversal(root.left);
            System.out.println(root.val);
            inOrderTraversal(root.right);
        }
    }

    //后序遍历
    public void postOrderTraversal(TreeNode root) {
        if (root != null) {
            postOrderTraversal(root.left);
            postOrderTraversal(root.right);
            System.out.println(root.val);
        }
    }

    //前序遍历
    public void preOrderTraversal(TreeNode root) {
        if (root != null) {
            System.out.println(root.val);
            preOrderTraversal(root.left);
            preOrderTraversal(root.right);
        }
    }

    //获取树中节点的个数
    int size1(TreeNode root) {
        if (root != null) {
            count++;
            size1(root.left);
            size1(root.right);
        }
        return count;
    }

    int size2(TreeNode root) {
        int count2 = 0;
        if (root == null) {
            return 0;
        }
        count2 = count2 + 1;
        count2 = size2(root.left) + count2;
        count2 = size2(root.right) + count2;
        return count2;
    }

    int size(TreeNode root) {

        if (root == null) {
            return 0;
        }
        count++;
        size(root.left);
        size(root.right);
        return count;
    }

    int Size(TreeNode root) {
        int count = 0;
        if (root == null) {
            return 0;
        }
        count = Size(root.left) + Size(root.right) + 1;
        return count;
    }

    //获取叶子节点的个数
    int getLeafNodeCount1(TreeNode root) {
        if (root != null) {
            if (root.left == null && root.right == null) {
                count++;
            }
            getLeafNodeCount1(root.left);
            getLeafNodeCount1(root.right);
        }
        return count;
    }

    int getLeafNodeCount2(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            if (root.left == null && root.right == null) {
                return 1;
            }
            return getLeafNodeCount2(root.left) + getLeafNodeCount2(root.right);
        }
    }

    int getLeafNodeCount(TreeNode root) {
        int count = 0;
        if (root == null) {
            return 0;
        }

        if (root.left == null && root.right == null) {
            return 1;
        }
        count += getLeafNodeCount(root.left);
        count += getLeafNodeCount(root.right);
        return count;
    }

    /**
     * 获取第K层节点的个数
     *
     * @param root
     * @return
     */
    int getKLevelNodeCount(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left, k - 1) + getKLevelNodeCount(root.right, k - 1);
    }

    //获取二叉树的高度
    int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return getHeight(root.left) > getHeight(root.right) ? getHeight(root.left) + 1 : getHeight(root.right) + 1;
        //递归次数太多
    }

    //获取二叉树的高度
    //时间复杂度O（n）
    //空间复杂度（logn）
    int getHeight2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int Height_left = getHeight2(root.left);
        int Height_right = getHeight2(root.right);
        return Height_left > Height_right ? Height_left + 1 : Height_right + 1;
    }

    //检测值为value的元素是否存在
    TreeNode find(TreeNode root, char val) {
        if (root == null) {
            return null;
        }
        if (root.val == val) {
            return root;
        }
        TreeNode ret = find(root.left, val);
        if (ret != null) {
            return ret;
        }
        ret = find(root.right, val);
        if (ret != null) {
            return ret;
        }
        return null;
    }

    /**
     * 是不是完全二叉树
     *
     * @param root
     * @return
     */
    boolean isCompleteTree(TreeNode root) {
        if (root == null) return true;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode top = queue.poll();
            if (top != null) {
                queue.offer(top.left);
                queue.offer(top.right);
            } else {
                break;
            }
        }
        while (!queue.isEmpty()) {
            TreeNode top = queue.poll();
            if (top != null) {
                return false;
            }
        }
        return true;
    }

    /**
     * 层序遍历
     */
    public void levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return;
        }
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val + " ");
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }

    public List<List<Character>> levelOrder2(TreeNode root) {
        List<List<Character>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();//这个值代表当前层有多少个节点
            List<Character> list = new ArrayList<>();
            while (size != 0) {
                TreeNode cur = queue.poll();
                list.add(cur.val);
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(list);
        }
        return ret;
    }

    /**
     * 最近公共祖先
     *
     * @param root
     * @param p
     * @param q
     * @return
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }

        if (root == p || root == q) {
            return root;
        }

        TreeNode leftT = lowestCommonAncestor(root.left, p, q);
        TreeNode rightT = lowestCommonAncestor(root.right, p, q);
        //在两侧
        if (leftT != null && rightT != null) {
            return root;
        } else if (leftT != null) {
            return leftT;
        } else {
            return rightT;
        }
    }

    //root:根节点，  node:指定的节点    ，stack：存放指定节点的路径
    public boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if (root == null || node == null) {
            return false;
        }
        stack.push(root);
        if (root == node) {
            return true;
        }
        boolean flg = getPath(root.left, node, stack);
        if (flg) {
            return true;
        }
        flg = getPath(root.right, node, stack);
        if (flg) {
            return true;
        }
        stack.pop();
        return false;
    }

    public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        getPath(root, p, stack1);
        Stack<TreeNode> stack2 = new Stack<>();
        getPath(root, q, stack2);
        int size1 = stack1.size();
        int size2 = stack2.size();
        if (size1 > size2) {
            int size = size1 - size2;
            while (size != 0) {
                //出第一个栈里面的元素
                stack1.pop();
                size--;
            }
            while (!stack1.isEmpty() && !stack2.isEmpty()) {
                //判断地址
                if (stack1.peek() == stack2.peek()) {
                    return stack1.pop();
                } else {
                    stack1.pop();
                    stack2.pop();
                }
            }
            return null;
        } else {
            int size = size2 - size1;
            while (size != 0) {
                //出第一个栈里面的元素
                stack2.pop();
                size--;
            }
            while (!stack1.isEmpty() && !stack2.isEmpty()) {
                //判断地址
                if (stack1.peek() == stack2.peek()) {
                    return stack1.pop();
                } else {
                    stack1.pop();
                    stack2.pop();
                }
            }
            return null;
        }
    }

    /**
     * 二叉搜索树转化为排序的双向链表
     */
    TreeNode prev = null;

    public void inorder(TreeNode pCur) {
        if (pCur == null) {
            return;
        }
        inorder(pCur.left);
        //打印
        pCur.left = prev;
        if (prev != null) {
            prev.right = pCur;
        }

        prev = pCur;

        inorder(pCur.right);
    }

    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) {
            return null;
        }
        inorder(pRootOfTree);
        TreeNode head = pRootOfTree;
        while (head.left != null) {
            head = head.left;
        }
        return head;
    }

    /**
     * 根据前序和中序遍历创建一棵二叉树
     */
    public int preIndex = 0;

    public TreeNode createTreeByPandI(char[] preorder, char[] inorder, int inbegin, int inend) {
        if (inbegin > inend) {
            //如果满足这个条件说明没有左树或者右树
            return null;
        }
        TreeNode root = new TreeNode(preorder[preIndex]);
        //找到根在中序遍历的位置
        int rootIndex = findIndexOfI(inorder, inbegin, inend, preorder[preIndex]);
        if (rootIndex == -1) {
            return null;
        }
        preIndex++;
        //分别创建左子树和右子树
        root.left = createTreeByPandI(preorder, inorder, inbegin, rootIndex - 1);
        root.right = createTreeByPandI(preorder, inorder, rootIndex + 1, inend);
        return root;
    }

    private int findIndexOfI(char[] inorder, int inbegin, int inend, int key) {
        for (int i = inbegin; i <= inend; i++) {
            if (inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }

    public TreeNode buildTree(char[] preorder, char[] inorder) {
        if (preorder == null || inorder == null) {
            return null;
        }
        return createTreeByPandI(preorder, inorder, 0, inorder.length - 1);
    }

    /**
     * 非递归前序遍历
     *
     * @param root
     */
    public void preOrderTraversalNor(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
    }

    public void InOrderTraversalNor(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.println(top.val + " ");
            cur = top.right;
        }
    }

    public void PostOrderTraversalNor(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode pre = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            //如果当前节点的右子树被打印过或者遍历过 直接可以弹出
            if (top.right == null || top.right == pre) {
                stack.pop();
                System.out.print(top.val + " ");
                pre = top;//记录最近一次打印的节点
            } else {
                cur = top.right;
            }
        }
    }
}
